<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户公司" prop="companyName">
        <el-input v-model="queryParams.companyName" placeholder="请输入客户公司" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="订单金额" prop="orderMoney">
        <el-input v-model="queryParams.orderMoney" placeholder="请输入订单金额" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="销售人" prop="saleBy">
        <el-input v-model="queryParams.saleBy" placeholder="请输入销售人" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="联系方式" prop="telNum">
        <el-input v-model="queryParams.telNum" placeholder="请输入联系方式" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="销售时间" prop="saleTime">
        <el-date-picker clearable v-model="queryParams.saleTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择销售时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['base:order:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['base:order:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['base:order:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['base:order:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="id" />
      <el-table-column label="客户公司" align="center" prop="companyName" />
      <el-table-column label="订单金额" align="center" prop="orderMoney" />
      <el-table-column label="销售人" align="center" prop="saleBy" />

      <el-table-column label="联系方式" align="center" prop="telNum" />
      <el-table-column label="销售时间" align="center" prop="saleTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.saleTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['base:order:edit']">修改</el-button> -->
          <el-button link type="primary" icon="Edit" @click="handleDetail(scope.row)"
            v-hasPermi="['base:order:edit']">详情</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['base:order:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改订单操作对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户公司" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入客户公司" />
        </el-form-item>
        <el-form-item label="订单金额" prop="orderMoney">
          <el-input v-model="form.orderMoney" placeholder="请输入订单金额" />
        </el-form-item>
        <el-form-item label="销售人" prop="saleBy">
          <el-input v-model="form.saleBy" placeholder="请输入销售人" />
        </el-form-item>

        <el-form-item label="联系方式" prop="telNum">
          <el-input v-model="form.telNum" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="销售时间" prop="saleTime">
          <el-date-picker clearable v-model="form.saleTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择销售时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <div>
          <div class="flex items-center mb-2">
            <span class="mr-2 font-bold">详情</span>
            <el-button circle type="primary" plain icon="plus" @click="addOrderItem"></el-button>
          </div>
          <div v-for="(item, index) in orderItemList" :key="index" class="mb-2">
            <span class="mr-2">类型</span><el-select v-model="item.fruitType" style="width: 80px;">
              <el-option v-for="dict in base_tree_type" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
            <span class="mx-2">品种</span><el-select v-model="item.fruitBreed" style="width: 80px;">
              <el-option v-for="dict in base_fruit_breed" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
            <span class="mx-2">单价</span><el-input v-model="item.unitPrice" style="width: 70px;"></el-input>
            <span class="mx-1">数量</span><el-input v-model.number="item.saleCount" style="width: 70px;"></el-input>
          </div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="订单详情" v-model="openDetail" width="500px" append-to-body>
      <div class="flex justify-between items-center mb-2" v-for="item in detailList">
        <div class="">单价：{{ item.unitPrice }}元/kg</div>
        <div class="">数量：{{ item.unitPrice }}kg</div>
        <div class="flex items-center">
          <div>果品类型：</div>
          <dict-tag :options="base_tree_type" :value="item.fruitType" />
        </div>
        <div class="flex items-center">
          <div>果品品种：</div>
          <dict-tag :options="base_fruit_breed" :value="item.fruitBreed" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/base/order";

const { proxy } = getCurrentInstance();
const { base_tree_type, base_fruit_breed } = proxy.useDict('base_tree_type', 'base_fruit_breed');

const orderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    companyName: null,
    orderMoney: null,
    saleBy: null,
    telNum: null,
    saleTime: null
  },
  rules: {
    companyName: [
      { required: true, message: "客户公司不能为空", trigger: "blur" }
    ],
    saleBy: [
      { required: true, message: "销售人不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "销售时间不能为空", trigger: "blur" }
    ],
    telNum: [
      { required: true, message: "联系方式不能为空", trigger: "blur" }
    ],
    saleTime: [
      { required: true, message: "销售时间不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);
const detailList = ref([])
const openDetail = ref(false)
const handleDetail = (row) => {
  detailList.value = row.orderItemList
  openDetail.value = true
}
const orderItemList = ref([])
const addOrderItem = () => {
  orderItemList.value.push({
    fruitType: '',
    fruitBreed: '',
    unitPrice: '',
    saleCount: '',
  })
}
/** 查询订单操作列表 */
function getList() {
  loading.value = true;
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    companyName: null,
    orderMoney: null,
    saleBy: null,
    createTime: null,
    remark: null,
    telNum: null,
    saleTime: null
  };
  orderItemList.value = []
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单操作";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getOrder(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改订单操作";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        form.value.orderItemList = orderItemList.value
        console.log(form.value);
        addOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除订单操作编号为"' + _ids + '"的数据项？').then(function () {
    return delOrder(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('base/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

getList();
</script>
